import React, { useState, useEffect } from 'react';
import { Upload, Modal } from 'antd';
import ImgCrop from 'antd-img-crop';
import 'antd/es/modal/style';
import 'antd/es/slider/style';

import { getdownLoadUrl, queryByIdFile } from '@/services/file';

interface file {
  [file: string]: string | number | any;
}

interface UploadProps {
  limit?: number;
  value?: string;
  onChange?: any;
  fileLists?: file[];
  type?: boolean;
  render?: React.ReactNode;
  disabled?: boolean;
  aspect?: number;
  listType?: string | undefined | null;
}

interface FileObj {
  url?: string;
  name?: string;
}

/**
 * 根据接口返回的文件数据组装一个上传组件需要的文件数据
 * @param respObj 上传成功返回类型，格式：{id:"xxx", name:"xxx", type:"pdf", url:"xxx" }
 * @param uploadedObj 上传组件需要的文件数据，如果该值为空则创建一个新的
 * @returns {{}}
 */
function makeupUploadedObjByResponseObj(respObj: file, uploadedObj = null) {
  const obj: file = uploadedObj ?? { uid: respObj.id };
  obj.id = respObj.id;
  obj.name = respObj.name;
  obj.url = getdownLoadUrl(respObj.id);
  obj.type = respObj.type;
  obj.thumbUrl = getdownLoadUrl(respObj.id);
  obj.status = 'done';
  obj.response = {
    data: [respObj],
  };
  obj.made = 1; // 是否是组装好的数据
  return obj;
}

/**
 * 获取服务端传递回来的的id
 * @param response
 */
function getId(response: file) {
  return response?.response?.data?.[0]?.id;
}

const UplodFile: React.FC<UploadProps> = props => {
  const [fileList, setFileList] = useState<file[]>([]);
  const [fileObj, setFileObj] = useState<FileObj>({});

  const { limit = 1, value, type, render, disabled, aspect, listType } = props;

  /**
   * 文件改变
   * @param fileList
   */
  const onChange = ({ fileList: newFileList }: any) => {
    if (limit == 1) {
      props?.onChange(newFileList?.length ? getId(newFileList[0]) : '');
    } else {
      props?.onChange(
        newFileList?.length
          ? newFileList.map((el, index) => ({
              key: index + 1,
              value: getId(el),
            }))
          : '',
      );
    }

    if (listType == 'picture') {
    } else {
      setFileList(newFileList);
    }
  };

  /**
   * 监听文件改变
   */
  // thinking： value 作为 string 或者 [{key,value}] 形式作为多个图片逻辑处理
  // 通过props.onChange 来处理 删除的参数或者其他问题
  useEffect(() => {
    if (limit == 1) {
      if (value && typeof value === 'string') {
        // 获取文件
        queryByIdFile({ id: value }).then(res => {
          if (res?.responseCode == 200 && res?.data) {
            setFileList([makeupUploadedObjByResponseObj(res?.data)]);
          }
        });
      }
    } else {
      if (value && Array.isArray(value) && value.every(el => el.value)) {
        // 获取文件;
        let arr: any = [];
        value.forEach(element => {
          arr.push(
            new Promise((resolve, reject) => {
              if (element) {
                queryByIdFile({ id: element.value }).then(res => {
                  if (res?.responseCode == 200 && res?.data) {
                    resolve(res?.data);
                  } else {
                    reject({});
                  }
                });
              }
            }),
          );
        });

        Promise.all(arr).then(res => {
          let arrl: any = [];
          res?.forEach((el: any) => {
            if (el) {
              arrl.push(makeupUploadedObjByResponseObj(el));
            }
          });
          setFileList(arrl);
        });
      }
    }
  }, [value]);

  /**
   * 文件查看
   * @param file
   */
  const onPreview = async file => {
    let src = file.url;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    setFileObj({
      url: src,
      name: file?.name,
    });
  };

  /**
   * 文件删除
   * @param file
   */
  const onRemove = async file => {
    try {
      await new Promise((resolve, reject) => {
        resolve();
      });
    } catch {
      return false;
    }
  };

  let defaultProps: any = {
    action: '/sealCuttingApi/file/uploadFile',
    listType: 'picture-card',
    accept: 'image/jpg, image/jpeg,image/bmp, image/png',
    fileList,
    onChange,
    onPreview,
    onRemove,
    disabled,
  };

  /**
   * 关闭文件查看
   */
  const handleCancel = () => {
    setFileObj({});
  };

  if (listType == 'picture') {
    defaultProps.listType = listType;
  }

  return (
    <div>
      {type ? (
        <ImgCrop rotate aspect={aspect}>
          <Upload {...defaultProps}>{fileList.length < limit && (render || '+ Upload')}</Upload>
        </ImgCrop>
      ) : (
        <Upload {...defaultProps}>{fileList.length < limit && (render || '+ Upload')}</Upload>
      )}
      <Modal title="展示图片" visible={Boolean(fileObj?.url)} footer={false} onCancel={handleCancel} width="540px">
        <div className="img_model">
          <img src={fileObj?.url} alt="" />
          <div>{fileObj?.name}</div>
        </div>
      </Modal>
    </div>
  );
};

export default UplodFile;
